<template>
  <div class="students-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="学号">
          <el-input
            v-model="searchForm.sno"
            placeholder="请输入学号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input
            v-model="searchForm.sname"
            placeholder="请输入姓名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="性别">
          <el-select
            v-model="searchForm.sex"
            placeholder="请选择性别"
            clearable
            style="width: 120px"
          >
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="系名">
          <el-input
            v-model="searchForm.dept"
            placeholder="请输入系名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button type="success" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增学生
          </el-button>
          <el-button type="warning" @click="handleBatchImport">
            <el-icon><Upload /></el-icon>
            批量导入
          </el-button>
          <el-button type="info" @click="handleExport">
            <el-icon><Download /></el-icon>
            导出Excel
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <el-table
        :data="tableData"
        v-loading="loading"
        stripe
        border
        style="width: 100%"
      >
        <el-table-column prop="sno" label="学号" width="120" />
        <el-table-column prop="sname" label="姓名" width="120" />
        <el-table-column prop="sex" label="性别" width="80" />
        <el-table-column prop="age" label="年龄" width="80" />
        <el-table-column prop="dept" label="系名" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleEdit(row)"
            >
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row)"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="学号" prop="sno">
          <el-input
            v-model="form.sno"
            placeholder="请输入学号"
            :disabled="isEdit"
          />
        </el-form-item>
        <el-form-item label="姓名" prop="sname">
          <el-input v-model="form.sname" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="form.sex" placeholder="请选择性别">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number
            v-model="form.age"
            :min="16"
            :max="100"
            placeholder="请输入年龄"
          />
        </el-form-item>
        <el-form-item label="系名" prop="dept">
          <el-input v-model="form.dept" placeholder="请输入系名" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 批量导入对话框 -->
    <el-dialog
      title="批量导入学生"
      v-model="batchImportVisible"
      width="600px"
      @close="handleBatchImportClose"
    >
      <div class="batch-import-content">
        <el-alert
          title="导入说明"
          type="info"
          :closable="false"
          style="margin-bottom: 20px"
        >
          <template #default>
            <p>1. 请下载模板文件，按照模板格式填写学生信息</p>
            <p>2. 支持Excel文件格式(.xlsx, .xls)</p>
            <p>3. 学号不能重复，系统会自动检查</p>
          </template>
        </el-alert>
        
        <div class="template-download" style="margin-bottom: 20px">
          <el-button type="primary" @click="downloadTemplate">
            <el-icon><Download /></el-icon>
            下载模板
          </el-button>
        </div>
        
        <el-upload
          ref="uploadRef"
          :auto-upload="false"
          :show-file-list="true"
          :limit="1"
          accept=".xlsx,.xls"
          :on-change="handleFileChange"
          :on-remove="handleFileRemove"
          drag
        >
          <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
          <div class="el-upload__text">
            将Excel文件拖拽到此处，或<em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              只能上传xlsx/xls文件，且不超过10MB
            </div>
          </template>
        </el-upload>
        
        <div v-if="previewData.length > 0" class="preview-section" style="margin-top: 20px">
          <h4>数据预览（前5条）：</h4>
          <el-table :data="previewData.slice(0, 5)" border size="small">
            <el-table-column prop="sno" label="学号" width="120" />
            <el-table-column prop="sname" label="姓名" width="100" />
            <el-table-column prop="sex" label="性别" width="80" />
            <el-table-column prop="age" label="年龄" width="80" />
            <el-table-column prop="dept" label="系名" />
          </el-table>
          <p style="margin-top: 10px; color: #666;">共 {{ previewData.length }} 条数据</p>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchImportVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="handleBatchImportSubmit" 
            :loading="batchImportLoading"
            :disabled="previewData.length === 0"
          >
            导入数据
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Edit, Delete, Upload, Download, UploadFilled } from '@element-plus/icons-vue'
import { useStudentStore } from '@/stores/student'
import * as XLSX from 'xlsx'

export default {
  name: 'Students',
  components: {
    Search,
    Refresh,
    Plus,
    Edit,
    Delete,
    Upload,
    Download,
    UploadFilled
  },
  setup() {
    const studentStore = useStudentStore()
    const submitLoading = ref(false)
    const dialogVisible = ref(false)
    const isEdit = ref(false)
    const formRef = ref()
    
    // 批量导入相关
    const batchImportVisible = ref(false)
    const batchImportLoading = ref(false)
    const previewData = ref([])
    const uploadRef = ref(null)
    
    const form = reactive({
      sno: '',
      sname: '',
      sex: '',
      age: null,
      dept: ''
    })
    
    const dialogTitle = computed(() => {
      return isEdit.value ? '编辑学生' : '新增学生'
    })
    
    const rules = {
      sno: [
        { required: true, message: '请输入学号', trigger: 'blur' },
        { pattern: /^\d{8,12}$/, message: '学号应为8-12位数字', trigger: 'blur' }
      ],
      sname: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
        { min: 2, max: 10, message: '姓名长度在2-10个字符', trigger: 'blur' }
      ],
      sex: [
        { required: true, message: '请选择性别', trigger: 'change' }
      ],
      age: [
        { required: true, message: '请输入年龄', trigger: 'blur' },
        { type: 'number', min: 16, max: 100, message: '年龄应在16-100之间', trigger: 'blur' }
      ],
      dept: [
        { required: true, message: '请输入系名', trigger: 'blur' },
        { min: 2, max: 20, message: '系名长度在2-20个字符', trigger: 'blur' }
      ]
    }
    
    // 搜索
    const handleSearch = () => {
      studentStore.setPagination(1, studentStore.pageSize)
      studentStore.fetchStudents()
    }
    
    // 重置
    const handleReset = () => {
      studentStore.resetSearch()
      studentStore.fetchStudents()
    }
    
    // 新增
    const handleAdd = () => {
      isEdit.value = false
      dialogVisible.value = true
      resetForm()
    }
    
    // 编辑
    const handleEdit = (row) => {
      isEdit.value = true
      dialogVisible.value = true
      Object.keys(form).forEach(key => {
        form[key] = row[key]
      })
    }
    
    // 删除
    const handleDelete = (row) => {
      ElMessageBox.confirm(
        `确定要删除学生 ${row.sname}(${row.sno}) 吗？`,
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          const result = await studentStore.removeStudent(row.sno)
          if (result.success) {
            ElMessage.success(result.message)
          } else {
            ElMessage.error(result.message)
          }
        } catch (error) {
          ElMessage.error('删除失败')
        }
      })
    }
    
    // 提交表单
    const handleSubmit = async () => {
      if (!formRef.value) return
      
      try {
        await formRef.value.validate()
        submitLoading.value = true
        
        let result
        if (isEdit.value) {
          result = await studentStore.modifyStudent(form.sno, form)
        } else {
          result = await studentStore.createStudent(form)
        }
        
        if (result.success) {
          ElMessage.success(result.message)
          dialogVisible.value = false
        } else {
          ElMessage.error(result.message)
        }
      } catch (error) {
        ElMessage.error('表单验证失败')
      } finally {
        submitLoading.value = false
      }
    }
    
    // 重置表单
    const resetForm = () => {
      Object.keys(form).forEach(key => {
        form[key] = key === 'age' ? null : ''
      })
      if (formRef.value) {
        formRef.value.clearValidate()
      }
    }
    
    // 关闭对话框
    const handleDialogClose = () => {
      resetForm()
    }
    
    // 分页大小改变
    const handleSizeChange = (size) => {
      studentStore.setPagination(1, size)
      studentStore.fetchStudents()
    }
    
    // 当前页改变
    const handleCurrentChange = (page) => {
      studentStore.setPagination(page, studentStore.pageSize)
      studentStore.fetchStudents()
    }
    
    // 批量导入相关方法
    const handleBatchImport = () => {
      batchImportVisible.value = true
      previewData.value = []
    }
    
    const handleBatchImportClose = () => {
      previewData.value = []
      if (uploadRef.value) {
        uploadRef.value.clearFiles()
      }
    }
    
    const downloadTemplate = () => {
      // 创建模板数据
      const templateData = [
        {
          '学号': '2021001',
          '姓名': '张三',
          '性别': '男',
          '年龄': 20,
          '系名': '计算机系'
        },
        {
          '学号': '2021002', 
          '姓名': '李四',
          '性别': '女',
          '年龄': 19,
          '系名': '数学系'
        }
      ]
      
      // 创建工作簿
      const wb = XLSX.utils.book_new()
      const ws = XLSX.utils.json_to_sheet(templateData)
      XLSX.utils.book_append_sheet(wb, ws, '学生信息模板')
      
      // 下载文件
      XLSX.writeFile(wb, '学生信息导入模板.xlsx')
      ElMessage.success('模板下载成功')
    }
    
    const handleFileChange = (file) => {
      const reader = new FileReader()
      reader.onload = (e) => {
        try {
          const data = new Uint8Array(e.target.result)
          const workbook = XLSX.read(data, { type: 'array' })
          const sheetName = workbook.SheetNames[0]
          const worksheet = workbook.Sheets[sheetName]
          const jsonData = XLSX.utils.sheet_to_json(worksheet)
          
          // 转换数据格式
          const students = jsonData.map(row => ({
            sno: String(row['学号'] || row.sno || ''),
            sname: String(row['姓名'] || row.sname || ''),
            sex: String(row['性别'] || row.sex || ''),
            age: Number(row['年龄'] || row.age || 0),
            dept: String(row['系名'] || row.dept || '')
          }))
          
          // 数据验证
          const validStudents = students.filter(student => 
            student.sno && student.sname && student.sex && student.age && student.dept
          )
          
          if (validStudents.length === 0) {
            ElMessage.error('文件中没有有效的学生数据')
            return
          }
          
          if (validStudents.length < students.length) {
            ElMessage.warning(`共${students.length}条数据，其中${validStudents.length}条有效`)
          }
          
          previewData.value = validStudents
          ElMessage.success(`成功解析${validStudents.length}条学生数据`)
        } catch (error) {
          console.error('文件解析错误:', error)
          ElMessage.error('文件格式错误，请检查文件格式')
        }
      }
      reader.readAsArrayBuffer(file.raw)
    }
    
    const handleFileRemove = () => {
      previewData.value = []
    }
    
    const handleBatchImportSubmit = async () => {
      if (previewData.value.length === 0) {
        ElMessage.warning('请先上传文件')
        return
      }
      
      try {
        batchImportLoading.value = true
        await studentStore.batchImportStudents(previewData.value)
        ElMessage.success(`成功导入${previewData.value.length}条学生数据`)
        batchImportVisible.value = false
        previewData.value = []
        if (uploadRef.value) {
          uploadRef.value.clearFiles()
        }
        // 刷新学生列表
        await studentStore.fetchStudents()
      } catch (error) {
        console.error('批量导入失败:', error)
        ElMessage.error('批量导入失败: ' + (error.message || '未知错误'))
      } finally {
        batchImportLoading.value = false
      }
    }
    
    // 导出Excel
    const handleExport = () => {
      try {
        const exportData = studentStore.students.map(item => ({
          '学号': item.sno,
          '姓名': item.sname,
          '性别': item.sex,
          '年龄': item.age,
          '系名': item.dept
        }))
        
        const ws = XLSX.utils.json_to_sheet(exportData)
        const wb = XLSX.utils.book_new()
        XLSX.utils.book_append_sheet(wb, ws, '学生列表')
        
        const fileName = `学生列表_${new Date().toISOString().slice(0, 10)}.xlsx`
        XLSX.writeFile(wb, fileName)
        
        ElMessage.success('导出成功')
      } catch (error) {
        console.error('导出失败:', error)
        ElMessage.error('导出失败')
      }
    }
    
    onMounted(() => {
      studentStore.fetchStudents()
    })
    
    return {
      loading: computed(() => studentStore.loading),
      submitLoading,
      dialogVisible,
      isEdit,
      formRef,
      searchForm: computed(() => studentStore.searchForm),
      form,
      tableData: computed(() => studentStore.students),
      currentPage: computed(() => studentStore.currentPage),
      pageSize: computed(() => studentStore.pageSize),
      total: computed(() => studentStore.total),
      dialogTitle,
      rules,
      batchImportVisible,
      batchImportLoading,
      previewData,
      uploadRef,
      handleSearch,
      handleReset,
      handleAdd,
      handleEdit,
      handleDelete,
      handleSubmit,
      handleDialogClose,
      handleSizeChange,
      handleCurrentChange,
      handleBatchImport,
      handleBatchImportClose,
      downloadTemplate,
      handleFileChange,
      handleFileRemove,
      handleBatchImportSubmit,
      handleExport
    }
  }
}
</script>

<style scoped>
.students-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.table-card {
  background: white;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-form-item) {
  margin-bottom: 15px;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
  text-align: left !important;
}

:deep(.el-table td) {
  text-align: left !important;
}

:deep(.el-table .cell) {
  text-align: left !important;
}
</style>